package com.jzo2o.trade.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.trade.dto.request.PayReqDTO;
import com.jzo2o.trade.enums.TradingStateEnum;
import com.jzo2o.trade.mapper.TradingMapper;
import com.jzo2o.trade.model.domain.Trading;
import com.jzo2o.trade.service.ITradingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * \* User: chy
 * \* Date: 2025/10/8  11:06
 * \* Description:支付订单服务实现类
 * \
 */
@Service
@Slf4j
public class TradingServiceImpl extends ServiceImpl<TradingMapper, Trading> implements ITradingService {

    @Resource
    private TradingMapper tradingMapper;
    /**
     * 创建支付订单
     *
     * @param reqDTO
     */
    @Override
    public Trading save(PayReqDTO reqDTO) {

        Trading trading = new Trading();
        //业务系统订单号
        trading.setProductOrderNo(reqDTO.getProductOrderNo());
        //支付渠道
        trading.setTradingChannel(reqDTO.getTradingChannel().getValue());
        //支付类型
        trading.setTradingType(reqDTO.getPayType().getValue());
        //交易金额
        trading.setTradingAmount(reqDTO.getTradingAmount());
        //备注
        trading.setMemo(reqDTO.getMemo());
        //交易单号  todo:这里待完善,简略生成
        trading.setTradingOrderNo(reqDTO.getProductOrderNo()+""+ RandomUtil.randomInt(1,10));
        //交易单状态
        trading.setTradingState(TradingStateEnum.DFC.getCode());
        //创建 时间
        trading.setCreateTime(LocalDateTime.now());
        tradingMapper.insert(trading);
        return trading;
    }


    @Override
    public List<Trading> selectPayStatus() {
        // 查询5分钟前已经支付的订单
        List<Trading> list = tradingMapper.selectList(Wrappers.<Trading>lambdaQuery()
                .eq(Trading::getTradingState, TradingStateEnum.FKZ.getCode())
                .le(Trading::getCreateTime, LocalDateTime.now().minusMinutes(5)));

        return list;
    }
}
